package ru.efko.dims.activity;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import ru.efko.dims.R;
import ru.efko.dims.domain.SensorDevice;
import ru.efko.dims.domain.SensorDeviceImpl;
import ru.efko.dims.util.ThreadLocalVariablesKeeper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class StartActivity extends Activity {

	private Button connectButton;
	private SensorDevice sensorDevice = new SensorDeviceImpl();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start);
		connectButton = Button.class.cast(findViewById(R.id.connectButton));
		addConnectListener();

	}

	private void addConnectListener() {
		connectButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					v.setEnabled(false);
					EditText addressEditText = EditText.class.cast(findViewById(R.id.addressEditText));
					EditText portEditText = EditText.class.cast(findViewById(R.id.portEditText));
					SocketAddress serverAddress;
					try {
						String ip = addressEditText.getText().toString();
						Integer port = Integer.valueOf(portEditText.getText().toString());
						serverAddress = new InetSocketAddress(ip, port);
					} catch (Exception e) {
						CharSequence text = "Значение адреса или порта некорректно";
						Toast.makeText(StartActivity.this, text, Toast.LENGTH_LONG).show();
						v.setEnabled(true);
						return;
					}
					ThreadLocalVariablesKeeper.setServerAddress(serverAddress);
					boolean isConnected = true;
					if (ThreadLocalVariablesKeeper.getSensorDevice() == null) {
						isConnected = sensorDevice.connect(serverAddress);
						if (!isConnected) {
							CharSequence text = "Соединение не установлено";
							Toast.makeText(StartActivity.this, text, Toast.LENGTH_LONG).show();
							return;
						}
						ThreadLocalVariablesKeeper.setSensorDevice(sensorDevice);

					}
					else {
						sensorDevice = ThreadLocalVariablesKeeper.getSensorDevice();
					}
					if (isConnected) {
						v.setEnabled(true);
						Intent startIntent = new Intent(StartActivity.this,
								GraphicsActivity.class);
						startActivity(startIntent);
					}
				} catch (Exception e) {
					CharSequence text = "Невозможно установить соединение";
					Toast.makeText(StartActivity.this, text, Toast.LENGTH_LONG).show();
					v.setEnabled(true);
					return;
				}
			}
		});
	}
}
